﻿using System.Linq;
using System.Configuration;
using System.Reflection;
using System;
using System.Net;
using System.Text;
using System.IO;

namespace DNSPod
{
    public class DnsPodBase
    {
        private DnsPodConfiguration _dnsPodInfo = DnsPodConfiguration.GetConfiguration();

        /// <summary>
        /// 以POST方式请求DNSPod API
        /// </summary>
        /// <param name="address">API地址,不包含域名,如:(https://dnsapi.cn/Info.Version)中的Info.Version</param>
        /// <param name="param">API所需的参数,不包含公共参数部分</param>
        /// <returns></returns>
        protected dynamic PostApiRequest(string address, object param = null)
        {
            address = _dnsPodInfo.Host + address;
            //公共参数
            var commonParam = new
            {
                login_email = _dnsPodInfo.Email,
                login_password = _dnsPodInfo.Password,
                format = _dnsPodInfo.Format,
                lang = _dnsPodInfo.Lang,
                error_on_empty = _dnsPodInfo.ErrorOnEmpty
            };
            var postParameters = GetApiParamDataString(commonParam);

            //若有额外参数，则将公共参数添加至参数请求中
            if (param != null)
            {
                postParameters = string.Format("{0}&{1}", postParameters, GetApiParamDataString(param));
            }
            var request = (HttpWebRequest)WebRequest.Create(address);
            request.Method = "POST";
            request.Headers.Add("content", "text/html; charset=UTF-8");
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = _dnsPodInfo.UserAgent;
            request.Timeout = 10000;
            var postData = Encoding.UTF8.GetBytes(postParameters);
            request.ContentLength = postData.Length;
            var smp = request.GetRequestStream();
            smp.Write(postData, 0, postData.Length);
            smp.Close();
            var response = (HttpWebResponse)request.GetResponse();
            var stream = new StreamReader(response.GetResponseStream(), encoding: System.Text.Encoding.UTF8);
            var responseString = stream.ReadToEnd();
            stream.Close();
            response.Close();
            dynamic obj = null;
            if (!string.IsNullOrWhiteSpace(responseString))
            {
                obj = JsonDynamicParser.FromJson(responseString);
            }
            return obj ?? new { status = new { code = 0, message = "DNSPod服务器接口异常，无法正常调用！" } };
        }

        /// <summary>
        /// 将API参数以字符串形式返回，参数之间以"&"操作符连接
        /// </summary>
        /// <param name="data">API参数对象</param>
        /// <returns>参数字符串</returns>
        private static string GetApiParamDataString(object data)
        {
            var dataString = string.Empty;
            if (data == null) return dataString;
            //利用反复取可读属性或实例，返回属性集合
            var objProperties = (from x in data.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) where x.CanRead select x).ToList();
            //将属性名与值拼接，返回string类型的数组
            var arrProValue = (from y in objProperties select string.Format("{0}={1}", y.Name, y.GetValue(data, new object[0]))).ToArray();
            //将数组以“&”连接
            dataString = string.Join("&", arrProValue);
            return dataString;
        }
    }

}
